﻿<%@ Page Title="" Language="C#" MasterPageFile="~/mpEShop.master" AutoEventWireup="true"
    CodeFile="Order.aspx.cs" Inherits="Order" %>

<%@ Register Assembly="mcGridView" Namespace="Mabna.WebControls" TagPrefix="cc2" %>
<%@ Register Src="UserControls/Signup.ascx" TagName="Signup" TagPrefix="uc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <table style="width: 100%">
        <tr>
            <td style="width: 25%; vertical-align: top">
                <center>
                    <div id="divCats">
                        <cc2:mcGridView runat="server" ID="grdCats" Width="100%" EvenClass="ui-widget-header ui-state-default cat"
                            OddClass="ui-widget-header ui-state-default cat" SortableClass="sort" HeaderClass="McGridHeader"
                            CurrentRowClass="ui-state-active" EmptyDataText="" StoreDatasInClient="true"
                            AllowPaging="True" PageIndex="1" PageSize="100">
                            <Columns>
                                <cc2:mcGridColumn HeaderText="" Width="300px">
                                    <ColumnTemplate>
                                        <div style="width:100%;height:40px;background-image:url('App_Themes/<#Theme#>/images/category/<#BgImage#>');background-repeat:no-repeat;background-position:right"><#Name#></div>
                                    </ColumnTemplate>
                                </cc2:mcGridColumn>
                            </Columns>
                        </cc2:mcGridView>
                    </div>
                </center>
            </td>
            <td style="width: 45%; vertical-align: top;">
                <center>
                    <div id="divProducts">
                        <table style="width: 100%; vertical-align: top;">
                            <tr>
                                <td>
                                    <span id="lblSelectedCat"></span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <img alt="" id="catImage" style="display: none; height: 200px;" />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <hr class="ui-widget-header" />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <cc2:mcGridView runat="server" ID="grdProducts" HeaderClass="McGridHeader" CurrentRowClass="ui-widget-hover"
                                        SelectedPageClass="mcGridSelectedPage" PageClass="mcGridPage" EmptyDataText=""
                                        StoreDatasInClient="true" AllowPaging="True" PageIndex="1" PageSize="10">
                                        <Columns>
                                            <cc2:mcGridColumn ID="PColumn" HeaderText="" Width="500px">
                                                <ColumnTemplate>
                                                    <table width="100%" class="PrdRow">
                                                        <tr>
                                                            <td width="80%">
                                                                <#Name#>
                                                                <br>
                                                                <span id="Description" style="font-size:x-small;font-weight:normal"><#Description#></span>
                                                            </td>
                                                            <td rowspan=2 style="height:30px;">
                                                                <#Price#> &euro;
                                                            </td>
                                                        </tr>
                                                        <tr><td></td></tr>
                                                    </table>
                                                </ColumnTemplate>
                                            </cc2:mcGridColumn>
                                        </Columns>
                                    </cc2:mcGridView>
                                </td>
                            </tr>
                        </table>
                    </div>
                </center>
            </td>
            <td style="width: 30%; vertical-align: top;">
                <center>
                    <div id="divBasket">
                        <h3>
                            IHRE BESTELLUNG
                            <hr class="ui-widget-header" />
                        </h3>
                        <div id="divBasketItems">
                            <cc2:mcGridView runat="server" ID="grdBasket" SelectedPageClass="mcGridSelectedPage"
                                PageClass="mcGridPage" EmptyDataText="" StoreDatasInClient="true" AllowPaging="True"
                                PageIndex="1" PageSize="10">
                                <Columns>
                                    <cc2:mcGridColumn HeaderText="" DataField="Name" Width="300px">
                                        <ColumnTemplate>
                                            <table width="100%" class="BasketRow">
                                                <tr>
                                                    <td width="10%">
                                                        <img src="Graphics/images/up16.png" onclick="incDecBasketItem(<#ID#> , 1)" style="cursor:pointer;" title="+1"/>
                                                        <br />
                                                        <img src="Graphics/images/down16.png" onclick="incDecBasketItem(<#ID#> , -1)" style="cursor:pointer;" title="-1"/>
                                                    </td>
                                                    <td width="10%">
                                                        <span id="Description" style="font-weight:normal"><#Cnt#>x</span>
                                                    </td>
                                                    <td width="55%" id=tdPrdName>
                                                        <span id="Description" style="font-weight:bold"><#Product.Name#></span><br/>
                                                    </td>
                                                    <td id="tdPrice" style="width: 25%; text-align:right">
                                                        <span id="Description" style="font-weight:normal">{0}</span>
                                                    </td>
                                                </tr>
                                            </table>
                                        </ColumnTemplate>
                                    </cc2:mcGridColumn>
                                </Columns>
                            </cc2:mcGridView>
                        </div>
                        <br />
                        <div>
                            <hr class="ui-widget-header" />
                            <table width="100%" style="text-align: right">
                                <tr>
                                    <td style="width: 150px">
                                        Gesamt :
                                    </td>
                                    <td>
                                        <label id="lblTotal_Order">
                                            0.00
                                        </label>
                                        &euro;
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" style="text-align: center; height: 50px">
                                        <button id="btnOrder" onclick="btnOrder_Click();return false;">
                                            BESTELLEN</button>
                                        <span style="width: 100%;" id="spnMessage" class=""></span>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </center>
            </td>
        </tr>
        <tr>
            <td colspan="3" style="text-align: left; padding: 10px">
                <label>
                    Mindestbestellwert :
                </label>
                <span id="spnMinOrder" style="font-weight: bold"></span>&euro;
            </td>
        </tr>
        <tr>
            <td colspan="3" style="text-align: center; padding: 10px">
                <div id="divPayOptions" runat="server">
                </div>
            </td>
        </tr>
    </table>
    <div id="dvPrdDetails">
        <div style="height: 320px">
            <div id="divProductShape" style="margin: 10px">
                <b>Form:</b>
                <table width="100%" style="border: 1px solid;">
                    <tr>
                        <td style="width: 50%; vertical-align: top">
                            <div id="chkProductShapeContainer">
                            </div>
                        </td>
                        <td style="width: 50%; vertical-align: top">
                            <div id="chkProductShapeContainer1">
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <div id="divProductExtra" style="margin: 10px">
                <b>Extra-Auswahl:</b>
                <table width="100%" style="border: 1px solid;">
                    <tr>
                        <td style="width: 50%; vertical-align: top">
                            <div id="chkProductExtraContainer">
                            </div>
                        </td>
                        <td style="width: 50%; vertical-align: top">
                            <div id="chkProductExtraContainer1">
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <div id="divProductReduce" style="margin: 10px">
                <b>Reduce:</b>
                <table width="100%" style="border: 1px solid;">
                    <tr>
                        <td style="width: 50%; vertical-align: top">
                            <div id="chkProductReduceContainer">
                            </div>
                        </td>
                        <td style="width: 50%; vertical-align: top">
                            <div id="chkProductReduceContainer1">
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <div>
            <b>Summe:</b> <span id="spnPrice"></span>&euro;
        </div>
    </div>
    <div id="divContact">
        <uc1:Signup ID="Signup1" runat="server" />
    </div>
    <div id="divOrderSave">
        <div style="width: 100%; min-height: 300px;">
            <table style="width: 100%">
                <tr>
                    <td>
                        <div class="boxBorder" style="width: 100%; min-height: 50px">
                            <input id="rdiDeliveryYes" type="radio" name="group1" checked="checked" onclick="calcBasketSummary();" />
                            <span style="font-size: small; font-weight: bold">Lieferung</span>
                            <input type="radio" name="group1" onclick="calcBasketSummary();" />
                            <span style="font-size: small; font-weight: bold">Selbstabholung</span>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="boxBorder" style="width: 100%; min-height: 80px">
                            <span style="font-size: small; font-weight: bold">Ihre Lieferadress :</span><br />
                            <br />
                            <span id="spnOrderConfirm_Name"></span>
                            <br />
                            <span id="spnOrderConfirm_Address"></span>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td id="tdOrderConfirm_Discount">
                        <div class="boxBorder" style="width: 100%; min-height: 70px">
                            <table style="width: 100%">
                                <tr>
                                    <td style="vertical-align: top; width: 135px">
                                        <span style="font-size: small; font-weight: bold">Rabatt und Punkte :</span>
                                    </td>
                                    <td style="text-align: left">
                                        <div id="divOrderConfirm_Discount" style="width: 100%; min-height: 70px">
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="boxBorder" style="width: 100%">
                            <span style="font-size: small; font-weight: bold">Ihre Bemerkung :</span><br />
                            <input style="width: 450px" type="text" id="spnOrderConfirm_Bemerkung" />
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <div style="width: 100%;">
            <table style="width: 100%; min-height: 100px;">
                <tr>
                    <td style="width: 200px; text-align: right">
                        Gesamt :
                    </td>
                    <td>
                        <label id="lblTotal">
                            0.00
                        </label>
                        &euro;
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right">
                        Rabatt 0 % :
                    </td>
                    <td style="color: Red;">
                        <label id="lblDiscount">
                            0.00
                        </label>
                        &euro;
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right">
                        Zustellgebühr :
                    </td>
                    <td>
                        <label id="lblAddition">
                            0.00
                        </label>
                        &euro;
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <hr class="ui-widget-header" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right">
                        zu zahlender Betrag :
                    </td>
                    <td>
                        <label id="lblAmountPayable">
                            0.00
                        </label>
                        &euro;
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align: center">
                        <br />
                        <button id="btnspnOrderConfirm" onclick="onOrderSave();return false;">
                            Bestellung durchführen</button>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <div id="divCompanyClosed">
        <div style="width: 100%;">
            <span style="font-size: medium; font-weight: bold">Do you want to buy?</span>
        </div>
    </div>
    <script language="javascript" type="text/javascript">

        var basket = new Array();
        var order = new Object();
        var lastProductShapeChecked = null;

        $(document).ready(function () {
            mcGridView('<%=grdCats.ClientID%>').currentrowindexchanged(grdCatsRowClicked);
            mcGridView('<%=grdProducts.ClientID%>').currentrowindexchanged(grdProductsRowClicked);

            mcGridView('<%=grdBasket.ClientID%>').rowdatabound(grdBasketRowDataBound);

            cats = eval(cats);
            for (var i = 0; i < cats.length; i++)
                cats[i].Theme = '<%=Page.Theme%>';
            mcGridView('<%=grdCats.ClientID%>').bind(cats);
            mcGridView('<%=grdCats.ClientID%>').enCurrent(mcGridView('<%=grdCats.ClientID%>').getDataRows()[0]);
            grdCatsRowClicked();

            //Dialog
            $("#dvPrdDetails").dialog({
                autoOpen: false,
                width: 600,
                height: 500,
                modal: true,
                buttons: [
				{
				    text: "OK",
				    click: function () {
				        onProductDetailsOk();
				        $(this).dialog("close");
				    }
				},
				{
				    text: "Cancel",
				    click: function () {
				        $(this).dialog("close");
				    }
				}
			]
            });
            //
            $("#divContact").dialog({
                autoOpen: false,
                width: 600,
                height: 550,
                modal: true,
                title: 'Please fill this form '
            });

            $("#divOrderSave").dialog({
                autoOpen: false,
                width: 600,
                height: 600,
                modal: true,
                title: 'Bestelling Abgeschliessen'
            });

            $("#divCompanyClosed").dialog({
                autoOpen: false,
                width: 500,
                height: 200,
                modal: true,
                buttons: [
				{
				    text: "Vorverkauf",
				    click: function () {
				        OrderCallServer('GetContact■');
				        $(this).dialog("close");
				    }
				},
				{
				    text: "Abbrechen",
				    click: function () {
				        $(this).dialog("close");
				    }
				}
			]
            });


            $("#btnOrder").button();
            $("#btnspnOrderConfirm").button();

            $("#spnMinOrder").text(deliveryDistricts_MinOrderPrice);

            if (initialBasketItems != undefined) {
                for (var i = 0; i < initialBasketItems.length; i++) {
                    var basketItem = new Object();
                    basketItem.Product = new Object();

                    basketItem.ID = basket.length + 1;
                    basketItem.Product = new Object();
                    basketItem.Product.ID = initialBasketItems[i].Product.ID;
                    basketItem.Product.Name = initialBasketItems[i].Product.Name;
                    basketItem.Price = initialBasketItems[i].Product.Price;
                    basketItem.Cnt = 1;
                    addToBasket(basketItem);
                }
            }

        });


        function grdCatsRowClicked(sender, e) {
            var catProducts = new Array();
            var selectedCat = mcGridView('<%=grdCats.ClientID%>').getCurrentDataItem().ID;

            for (var i = 0; i < products.length; i++) {
                if (products[i].ProductCategory.ID == selectedCat) {
                    products[i].Price = parseFloat(products[i].Price).toFixed(2);
                    catProducts.push(products[i]);
                }
            }
            $('#lblSelectedCat').text(mcGridView('<%=grdCats.ClientID%>').getCurrentDataItem().Name);


            var Image = mcGridView('<%=grdCats.ClientID%>').getCurrentDataItem().Image;

            if (Image != '-4' && Image != 'undefined') {
                $f('catImage').style.display = '';
                $f('catImage').src = 'App_Themes/<%=Page.Theme%>/images/category/' + Image;
            }
            else {
                $f('catImage').style.display = 'none';
                $f('catImage').src = '';
            }

            var pcats = eval(catProducts);
            $(pcats).each(function () {
                if (this.Description == '-4') {
                    this.Description = '';
                }
            });
            mcGridView('<%=grdProducts.ClientID%>').bind(pcats);


        }
        function grdProductsRowClicked(sender, e) {
            var prdName = mcGridView('<%=grdProducts.ClientID%>').getCurrentDataItem().Name;

            var extras = new Array();
            var reduces = new Array();
            var shapes = new Array();

            var selectedProduct = mcGridView('<%=grdProducts.ClientID%>').getCurrentDataItem().ID;
            for (var i = 0; i < productExtra.length; i++) {
                if (productExtra[i].Product.ID == selectedProduct) {
                    if (productExtra[i].IsAdditional == true) {
                        extras.push(productExtra[i]);
                    }
                    else {
                        reduces.push(productExtra[i]);
                    }
                }
            }

            for (i = 0; i < productShapes.length; i++) {
                if (productShapes[i].Product.ID == selectedProduct) {
                    shapes.push(productShapes[i]);
                }
            }

            if (extras.length > 0) {
                $('#divProductExtra').show();

                $('#chkProductExtraContainer').html('');
                $('#chkProductExtraContainer1').html('');
                $.each(extras, function (key, value) {
                    var mode = key % 2;

                    if (mode == 0) {
                        $('#chkProductExtraContainer').append(
                           $(document.createElement('input')).attr({
                               id: 'chkExtra' + key
                              , value: 'false'
                              , type: 'checkbox'
                              , price: value.Price
                              , name: 'chkExtra'
                              , extraid: value.ID
                              , extraname: value.Ingredient.Name
                           }).click(function () {
                               var incDec = 0;
                               if ($(this).is(':checked') == true)
                                   incDec = parseFloat($(this).attr('price'));
                               else
                                   incDec = parseFloat($(this).attr('price') * -1);
                               var currentPrice = parseFloat($('#spnPrice').text());
                               $('#spnPrice').text(parseFloat(currentPrice + incDec).toFixed(2));
                           })
                        );
                        $('#chkProductExtraContainer').append($(document.createElement('label')).html(value.Ingredient.Name + ' (' + value.Price + ' &euro;)'));
                        $('#chkProductExtraContainer').append('<br/>');
                    }
                    else {

                        $('#chkProductExtraContainer1').append(
                           $(document.createElement('input')).attr({
                               id: 'chkExtra' + key
                              , value: 'false'
                              , type: 'checkbox'
                              , price: value.Price
                              , name: 'chkExtra'
                              , extraid: value.ID
                              , extraname: value.Ingredient.Name
                           }).click(function () {
                               var incDec = 0;
                               if ($(this).is(':checked') == true)
                                   incDec = parseFloat($(this).attr('price'));
                               else
                                   incDec = parseFloat($(this).attr('price') * -1);
                               var currentPrice = parseFloat($('#spnPrice').text());
                               $('#spnPrice').text(parseFloat(currentPrice + incDec).toFixed(2));
                           })
                        );
                        $('#chkProductExtraContainer1').append($(document.createElement('label')).html(value.Ingredient.Name + ' (' + value.Price + ' &euro;)'));
                        $('#chkProductExtraContainer1').append('<br/>');
                    }

                });
            }
            else {
                $('#divProductExtra').hide();
            }

            if (reduces.length > 0) {
                $('#divProductReduce').show();

                $('#chkProductReduceContainer').html('');
                $('#chkProductReduceContainer1').html('');
                $.each(reduces, function (key, value) {
                    var mode = key % 2;

                    if (mode == 0) {
                        $('#chkProductReduceContainer').append(
                           $(document.createElement('input')).attr({
                               id: 'chkReduce' + key
                              , value: 'false'
                              , type: 'checkbox'
                              , price: value.Price
                              , name: 'chkReduce'
                              , extraid: value.ID
                              , extraname: value.Ingredient.Name
                           }).click(function () {
                               var incDec = 0;
                               if ($(this).is(':checked') == true)
                                   incDec = parseFloat($(this).attr('price') * -1);
                               else
                                   incDec = parseFloat($(this).attr('price'));
                               var currentPrice = parseFloat($('#spnPrice').text());
                               $('#spnPrice').text(parseFloat(currentPrice + incDec).toFixed(2));
                           })
                        );
                        $('#chkProductReduceContainer').append($(document.createElement('label')).html(value.Ingredient.Name + ' (' + value.Price + ' &euro;)'));
                        $('#chkProductReduceContainer').append('<br/>');
                    }
                    else {

                        $('#chkProductReduceContainer1').append(
                           $(document.createElement('input')).attr({
                               id: 'chkReduce' + key
                              , value: 'false'
                              , type: 'checkbox'
                              , price: value.Price
                              , name: 'chkReduce'
                              , extraid: value.ID
                              , extraname: value.Ingredient.Name
                           }).click(function () {
                               var incDec = 0;
                               if ($(this).is(':checked') == true)
                                   incDec = parseFloat($(this).attr('price') * -1);
                               else
                                   incDec = parseFloat($(this).attr('price'));
                               var currentPrice = parseFloat($('#spnPrice').text());
                               $('#spnPrice').text(parseFloat(currentPrice + incDec).toFixed(2));
                           })
                        );
                        $('#chkProductReduceContainer1').append($(document.createElement('label')).html(value.Ingredient.Name + ' (' + value.Price + ' &euro;)'));
                        $('#chkProductReduceContainer1').append('<br/>');
                    }

                });
            }
            else {
                $('#divProductExtra').hide();
            }

            if (shapes.length > 0) {
                $('#divProductShape').show();
                $('#chkProductShapeContainer').html('');
                $('#chkProductShapeContainer1').html('');
                $.each(shapes, function (key, value) {
                    var mode = key % 2;

                    if (mode == 0) {
                        $('#chkProductShapeContainer').append(
                           $(document.createElement('input')).attr({
                               id: 'chkShape' + key
                              , value: 'false'
                              , type: 'radio'
                              , price: value.Price
                              , name: 'rdiShape'
                              , extraid: value.ID
                              , extraname: value.Shape.Name
                           }).click(function () {
                               var incDec = 0;
                               if ($(this).is(':checked') == true)
                                   incDec = parseFloat($(this).attr('price'));
                               else
                                   incDec = parseFloat($(this).attr('price') * -1);
                               var currentPrice = parseFloat($('#spnPrice').text());
                               var lastCheckedPrice = 0;
                               if (lastProductShapeChecked != null) {
                                   lastCheckedPrice = parseFloat(lastProductShapeChecked.attr('price'));
                               }
                               $('#spnPrice').text(parseFloat(currentPrice + incDec - lastCheckedPrice).toFixed(2));
                               lastProductShapeChecked = $(this);
                           })
                        );
                        $('#chkProductShapeContainer').append($(document.createElement('label')).html(value.Shape.Name + ' (' + value.Price + ' &euro;)'));
                        $('#chkProductShapeContainer').append('<br/>');
                    }
                    else {
                        $('#chkProductShapeContainer1').append(
                           $(document.createElement('input')).attr({
                               id: 'chkShape' + key
                              , value: 'false'
                              , type: 'radio'
                              , price: value.Price
                              , name: 'rdiShape'
                              , extraid: value.ID
                              , extraname: value.Shape.Name
                           }).click(function () {
                               var incDec = 0;
                               if ($(this).is(':checked') == true)
                                   incDec = parseFloat($(this).attr('price'));
                               else
                                   incDec = parseFloat($(this).attr('price') * -1);
                               var currentPrice = parseFloat($('#spnPrice').text());
                               var lastCheckedPrice = 0;
                               if (lastProductShapeChecked != null) {
                                   lastCheckedPrice = parseFloat(lastProductShapeChecked.attr('price'));
                               }
                               $('#spnPrice').text(parseFloat(currentPrice + incDec - lastCheckedPrice).toFixed(2));
                               lastProductShapeChecked = $(this);
                           })
                        );
                        $('#chkProductShapeContainer1').append($(document.createElement('label')).html(value.Shape.Name + ' (' + value.Price + ' &euro;)'));
                        $('#chkProductShapeContainer1').append('<br/>');
                    }

                });
                $('#chkShape0')[0].checked = true;
            }
            else {
                $('#divProductShape').hide();
            }

            if (reduces.length > 0 || extras.length > 0 || $('#drpProductShape option').length > 0) {
                $('#dvPrdDetails').dialog('option', 'title', prdName);
                $("#dvPrdDetails").dialog('open');
                $('#spnPrice').text(mcGridView('<%=grdProducts.ClientID%>').getCurrentDataItem().Price);
            }
            else {
                var basketItem = new Object();
                basketItem.Product = new Object();

                basketItem.ID = basket.length + 1;
                basketItem.Product = new Object();
                basketItem.Product.ID = mcGridView('<%=grdProducts.ClientID%>').getCurrentDataItem().ID;
                basketItem.Product.Name = mcGridView('<%=grdProducts.ClientID%>').getCurrentDataItem().Name;
                basketItem.Price = mcGridView('<%=grdProducts.ClientID%>').getCurrentDataItem().Price;
                basketItem.Cnt = 1;
                addToBasket(basketItem);
            }
        }

        function onProductDetailsOk() {
            var basketItem = new Object();
            basketItem.Product = new Object();

            basketItem.ID = basket.length + 1;
            basketItem.Product = new Object();
            basketItem.Product.ID = mcGridView('<%=grdProducts.ClientID%>').getCurrentDataItem().ID;
            basketItem.Product.Name = mcGridView('<%=grdProducts.ClientID%>').getCurrentDataItem().Name;
            basketItem.Price = parseFloat($('#spnPrice').text());
            basketItem.Cnt = 1;

            basketItem.Shape = new Object();
            basketItem.Shape.ID = null;
            if ($("input[name='rdiShape']:checked").length > 0) {
                basketItem.Shape.ID = $($("input[name='rdiShape']:checked")[0]).attr('extraid')
                basketItem.Shape.Name = $($("input[name='rdiShape']:checked")[0]).attr('extraname')
            }

            basketItem.OrderDetailItem = new Array();

            $("input[name='chkExtra']:checked").each(function (key, value) {
                var odi = new Object();
                odi.ProductExtra = new Object();
                odi.ProductExtra.ID = $(value).attr('extraid');
                odi.ProductExtra.Product = new Object();
                odi.ProductExtra.Product.Name = $(value).attr('extraname');
                odi.ProductExtra.IsAdditional = true;
                odi.Price = $(value).attr('Price')
                basketItem.OrderDetailItem.push(odi);
            });

            $("input[name='chkReduce']:checked").each(function (key, value) {
                var odi = new Object();
                odi.ProductExtra = new Object();
                odi.ProductExtra.ID = $(value).attr('extraid');
                odi.ProductExtra.Product = new Object();
                odi.ProductExtra.Product.Name = $(value).attr('extraname');
                odi.ProductExtra.IsAdditional = false;
                odi.Price = $(value).attr('Price')
                basketItem.OrderDetailItem.push(odi);
            });

            addToBasket(basketItem);
        }

        function addToBasket(basketItem) {
            basket.push(basketItem);
            calcBasketSummary_Order();
            mcGridView('<%=grdBasket.ClientID%>').bind(basket);
        }

        function grdBasketRowDataBound(sender, e) {
            if (e.RowType == 1) {
                if (e.RowDataItem.Shape != undefined && e.RowDataItem.Shape.Name != "") {
                    $(e.Row[0].cells['tdPrdName']).append('<span class="Shape">' + e.RowDataItem.Shape.Name + '</span>');
                    $(e.Row[0].cells['tdPrdName']).append('<br/>');
                }

                $(e.RowDataItem.OrderDetailItem).each(function (key, value) {
                    if (value.ProductExtra.IsAdditional == 1)
                        $(e.Row[0].cells['tdPrdName']).append('<span class="Extra">' + value.ProductExtra.Product.Name + ',' + '</span>');
                    else
                        $(e.Row[0].cells['tdPrdName']).append('<span class="Reduce">' + value.ProductExtra.Product.Name + ',' + '</span>');
                });

                $(e.Row[0].cells['tdPrice']).html(
                        $(e.Row[0].cells['tdPrice']).html().replace('{0}', parseFloat(e.RowDataItem.Cnt * e.RowDataItem.Price).toFixed(2)));
            }
        }
        function incDecBasketItem(itemID, amount) {

            $(basket).each(function (key, value) {
                if (value.ID == itemID) {
                    if (amount == 1)
                        basket[key].Cnt++;
                    else {
                        basket[key].Cnt--;
                        if (basket[key].Cnt == 0)
                            basket.splice(key, 1);
                    }
                }
            });
            calcBasketSummary_Order();
            mcGridView('<%=grdBasket.ClientID%>').bind(basket);
        }
        function calcBasketSummary_Order() {
            var totalprice = 0;

            $(basket).each(function (key, value) {
                totalprice = parseFloat((value.Cnt * parseFloat(value.Price)) + parseFloat(totalprice)).toFixed(2);
            });

            $('#lblTotal_Order').text(commafy(totalprice));
        }
        function calcBasketSummary() {
            var totalprice = 0;

            $(basket).each(function (key, value) {
                totalprice = parseFloat((value.Cnt * parseFloat(value.Price)) + parseFloat(totalprice)).toFixed(2);
            });

            var additionprice = 0;
            if ($('#rdiDeliveryYes')[0].checked) {
                additionprice = parseFloat(deliveryDistricts_MinOrderPrice) - parseFloat(totalprice);
                if (additionprice < 0)
                    additionprice = 0;
            }
            additionprice = parseFloat(additionprice).toFixed(2);

            var discountPrice = 0;
            var discountList = calcOrderSavingProcess_GetDiscountList();
            for (var i = 0; i < discountList.length; i++) {
                discountPrice = discountPrice + parseFloat(discountList[i].Price);
            }
            discountPrice = parseFloat(discountPrice).toFixed(2);

            payableprice = parseFloat(parseFloat(totalprice) + parseFloat(additionprice) - parseFloat(discountPrice)).toFixed(2);

            order.Price = totalprice;
            order.PriceDiscount = discountPrice;
            order.PriceAddition = additionprice;

            $('#lblTotal').text(commafy(totalprice));
            $('#lblAddition').text(commafy(additionprice));
            $('#lblDiscount').text(commafy(discountPrice));
            $('#lblAmountPayable').text(commafy(payableprice));
        }
        function btnOrder_Click() {
            if (IsCompanyOpen == true) {
                OrderCallServer('GetContact■');
            }
            else {
                $("#divCompanyClosed").dialog('open');
            }
        }

        function ContactInserted(contactID) {
            $("#divContact").dialog('close');

            order.Contact = new Object();
            order.Contact.ID = contactID;

            onOrderSavingProcess();
        }
        function saveOrderError(msg) {
            $("#divOrderSave").dialog('close');
            $('#spnMessage')
            .removeClass('success')
            .addClass('error')
            .html(msg);
            finishOrdering();
        }
        function saveOrderSuccess(msg) {
            $("#divOrderSave").dialog('close');
            $('#spnMessage')
            .removeClass('error')
            .addClass('success')
            .html(msg);
            finishOrdering();
        }

        function finishOrdering() {
            $('#btnOrder').hide();
            //location.reload();
        }

        function OrderReceive(data) {
            var command = data.split('■')[0];
            var args = data.split('■')[1];

            if (command == 'notLoggedIn') {
                $("#divContact").dialog('open');
            }
            else if (command == 'LoggedIn') {
                order.Contact = new Object();
                order.Contact.ID = args;

                onOrderSavingProcess();
            }
            else if (command == 'saveOrderCalculated') {
                onOrderSavingProcess_Calculated(args);
            }
            else if (command == 'saveOrderError') {
                saveOrderError(args);
            }
            else if (command == 'saveOrderSuccess') {
                saveOrderSuccess(args);
            }
        }
        function onOrderSave() {
            order.Description = $("#spnOrderConfirm_Bemerkung")[0].value;

            order.OrderDetail = basket;
            var discountListSelected = calcOrderSavingProcess_GetDiscountList();
            var discountList = new Array();
            for (var i = 0; i < discountListSelected.length; i++) {
                var discount = new Object();
                discount.ID = discountListSelected[i].ID
                discountList.push(discount);
            }

            OrderCallServer('InsertOrder■' + JSON.stringify(order) + '■' + JSON.stringify(discountList));
        }
        function onOrderSavingProcess() {
            order.OrderDetail = basket;
            OrderCallServer('CalculateOrder■' + JSON.stringify(order));
        }
        function onOrderSavingProcess_Calculated(args) {
            var orderCalculated = eval("(" + args + ')');
            deliveryDistricts_MinOrderPrice = parseFloat(orderCalculated.MinOrderPrice);
            $("#spnMinOrder").text(deliveryDistricts_MinOrderPrice);

            calcBasketSummary();

            $("#spnOrderConfirm_Name").text(orderCalculated.contact.FirstName + " " + orderCalculated.contact.LastName);
            var completeAddress = "";
            if (orderCalculated.contact.Address != null)
                completeAddress = completeAddress + orderCalculated.contact.Address;
            if (orderCalculated.contact.Street != null)
                completeAddress = completeAddress + " / " + orderCalculated.contact.Street;
            if (orderCalculated.contact.HomeNumber != null)
                completeAddress = completeAddress + " / " + orderCalculated.contact.HomeNumber;
            if (orderCalculated.contact.PostalCode != null)
                completeAddress = completeAddress + " - " + orderCalculated.contact.PostalCode;
            $("#spnOrderConfirm_Address").text(completeAddress);

            if (orderCalculated.discountShowList.length > 0) {
                $('#tdOrderConfirm_Discount').show();
                $('#divOrderConfirm_Discount').html('');

                var groupingCodes = new Array();
                for (var i = 0; i < orderCalculated.discountShowList.length; i++) {
                    var isFound = false;
                    for (var j = 0; j < groupingCodes.length; j++) {
                        if (orderCalculated.discountShowList[i].GroupingCode == groupingCodes[j]) {
                            isFound = true;
                        }
                    }
                    if (!isFound) {
                        groupingCodes.push(orderCalculated.discountShowList[i].GroupingCode);
                    }
                }

                for (var i = 0; i < groupingCodes.length; i++) {
                    var discountShowList_GroupingCode = new Array();
                    for (var j = 0; j < orderCalculated.discountShowList.length; j++) {
                        if (orderCalculated.discountShowList[j].GroupingCode == groupingCodes[i]) {
                            discountShowList_GroupingCode.push(orderCalculated.discountShowList[j]);
                        }
                    }

                    if (discountShowList_GroupingCode.length > 1) {
                        $('#divOrderConfirm_Discount').append(
                            $(document.createElement('select')).attr({
                                id: 'drpDiscount' + i,
                                name: 'drpDiscount',
                                onChange: 'calcBasketSummary();'
                            })
                        );

                        $('#drpDiscount' + i).append('<option value="" disabled="disabled" selected="selected">select a discount</option>');
                        for (var j = 0; j < discountShowList_GroupingCode.length; j++) {
                            $('#drpDiscount' + i).append('<option discountID="' + discountShowList_GroupingCode[j].ID + '" discountPrice="' + discountShowList_GroupingCode[j].DiscountPrice + '">' + discountShowList_GroupingCode[j].Caption + '</option>');
                        }
                    }
                    else {
                        $('#divOrderConfirm_Discount').append('<span name="spnDiscount" discountID="' + discountShowList_GroupingCode[0].ID + '" discountPrice="' + discountShowList_GroupingCode[0].DiscountPrice + '">' + discountShowList_GroupingCode[0].Caption + '</span>');
                    }

                    $('#divOrderConfirm_Discount').append('<br/><br/>');
                }
            }
            else {
                $('#tdOrderConfirm_Discount').hide();
            }

            calcBasketSummary();
            $("#divOrderSave").dialog('open');
        }

        function calcOrderSavingProcess_GetDiscountList() {
            var discountList = new Array();
            $("select[name='drpDiscount']").each(function (key, value) {
                if (value.selectedIndex != -1) {
                    var disc = new Object();
                    var selectedOption = value.options[value.selectedIndex];
                    if ($(selectedOption).attr('discountID') != undefined) {
                        disc.ID = $(selectedOption).attr('discountID');
                        disc.Price = $(selectedOption).attr('discountPrice');
                        discountList.push(disc);
                    }
                }
            });
            $("span[name='spnDiscount']").each(function (key, value) {
                var disc = new Object();
                disc.ID = $(value).attr('discountID');
                disc.Price = $(value).attr('discountPrice');
                discountList.push(disc);
            });

            return discountList;
        }
    </script>
</asp:Content>
